//
//  RAPEmoticonCollectionView.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/7/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

private let kCellID = "cell"

/// 便宜量，魔法数字
private let kMagnifierOffsetY: CGFloat = 10


class RAPEmoticonPresentationView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, RAPEmoticonPresentationCellDelegate {
    
    // MARK: - 自定义属性
    var onScrollingClosure: ((cellIndexPath: NSIndexPath) -> ())?
    
    // MARK: - 系统方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        // 对layout对象进行设置
        flowLayout.scrollDirection = .Horizontal
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        super.init(frame: frame, collectionViewLayout: flowLayout)
        getReady()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func getReady() {
        backgroundColor = UIColor.clearColor()
        
        // TODO: 还有一个UITextEffectsWindow，暂时不明白作用
        /*
        在UIRemoteKeyboardWindow上添加放大镜
        */
        UIApplication.sharedApplication().windows.last!.addSubview(magnifierView)
        // 隐藏放大镜
        magnifierView.hidden = true
        
        // 设置数据源，代理
        self.dataSource = self
        self.delegate = self
        // 注册cell
        registerClass(RAPEmoticonPresentationCell.self, forCellWithReuseIdentifier: kCellID)
        
        // 设置collection view
        pagingEnabled = true
        bounces = false
        showsHorizontalScrollIndicator = false
    }
    
    override func layoutSubviews() {
        /*
        一定要调用super，否则出现各种奇怪问题，例如不调用代理方法
        */
        super.layoutSubviews()
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = frame.size
    }
    
    // MARK: - 懒加载控件
    /// 放大镜
    private lazy var magnifierView: RAPEmoticonMagnifierView = {
        let magnifierView = NSBundle.mainBundle().loadNibNamed("RAPEmoticonMagnifierView", owner: nil, options: nil).last as! RAPEmoticonMagnifierView
        
        
        return magnifierView
        }()

}

// MARK: - UICollectionViewDataSource
extension RAPEmoticonPresentationView {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return RAPEmoticonKeyboardViewModel.sharedViewModel.tripleDArray.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return RAPEmoticonKeyboardViewModel.sharedViewModel.tripleDArray[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(kCellID, forIndexPath: indexPath) as! RAPEmoticonPresentationCell
        
        cell.indexPath = indexPath
        cell.delegate = self // 设置代理
        cell.emoticonsForCell = RAPEmoticonKeyboardViewModel.sharedViewModel.tripleDArray[indexPath.section][indexPath.item]
        
        return cell
    }
}

// MARK: - UIScrollViewDelegate
extension RAPEmoticonPresentationView {
    func scrollViewDidScroll(scrollView: UIScrollView) {

        /*
        注意，使用无动画代码滚动，可见cell只能有一个，
        然后用手滚动，可以同时有两个cell
        */
        if visibleCells().count != 2 {
            return
        }
        
        /*
        对于visibleCells这个方法来说，数组位置越靠前，实际显示的位置越靠后
        */
        let rearIndexPath = indexPathForCell(visibleCells().first!)
        let frontIndexPath = indexPathForCell(visibleCells().last!)
        
        let rearX = visibleCells().first?.frame.origin.x
        let frontX = visibleCells().last?.frame.origin.x
        
        
        if abs(scrollView.contentOffset.x - frontX!) > abs(scrollView.contentOffset.x - rearX!) { // 后面显示的多，抛出后面的cell
            onScrollingClosure?(cellIndexPath: rearIndexPath!)
        } else { // 前面显示的多，抛出前面的cell
            onScrollingClosure?(cellIndexPath: frontIndexPath!)
        }
    }
}

// MARK: - RAPEmoticonPresentationCellDelegate
extension RAPEmoticonPresentationView {
    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, emoticonButtonClicked: RAPEmoticonButton) {
        /*
        获取button在其superview中相对于UIRemoteKeyboard的坐标,
        注意，最后一个参数不能填self，因为对于collection view来说，button会滚动
        */
        let rect = UIApplication.sharedApplication().windows.last!.convertRect(emoticonButtonClicked.frame, fromView:emoticonButtonClicked.superview!)
        
        magnifierView.center.x = CGRectGetMidX(rect)
        magnifierView.frame.origin.y = CGRectGetMidY(rect) - magnifierView.bounds.height + kMagnifierOffsetY
        
        magnifierView.emoticonButton.emoticonModel = emoticonButtonClicked.emoticonModel
    }
    
    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, longPressBegan: UILongPressGestureRecognizer) {
        // 显示放大镜
        magnifierView.hidden = false
    }
    
    func emoticonPresentationCell(cell: RAPEmoticonPresentationCell, longPressEnded: UILongPressGestureRecognizer) {
        // 隐藏放大镜
        magnifierView.hidden = true
    }

}
